package com.spring.demo.security;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.spring.demo.util.Constant;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

import com.spring.demo.model.user.User;
import com.spring.demo.service.user.UserService;

/**
 * 登录授权成功后跳转到的类
 * @author ld2016
 *
 */
@Component("myAuthenticationSuccessHandler")
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

	private Map<String,String> authDispatcherMap;  //存放不同的角色登录成功后首次跳转的url
	
	private RequestCache requestCache = new HttpSessionRequestCache();
	
	@Resource(name = UserService.SERVICE_NAME)
	private UserService userService;
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		//获取用户权限
		Collection<? extends GrantedAuthority> authCollection = authentication.getAuthorities();
		if(authCollection.isEmpty()) {  //没有权限
			return ;
		}
		
		//认证成功后，获取用户信息并添加到session中，并修改用户信息
		UserDetails userDetails = (UserDetails) authentication.getPrincipal();
		List<User> users = userService.selectUser(userDetails.getUsername(), null);
		
		User user = users.get(0);
		user.setIsOnline(true);
		user.setLastLoginTime(new Timestamp(new Date().getTime()));
		
		request.getSession().setAttribute(Constant.LOGIN_USER, users.get(0));
		
		String url = null;
		
		//从别的请求页跳转过来的情况，savedRequest不为空
		/*SavedRequest savedRequest = requestCache.getRequest(request, response);
		if(savedRequest!=null) {
			url = savedRequest.getRedirectUrl();
		}
		*/
		/*
		 * 所有的角色都要加上前缀ROLE_
		 */
		authDispatcherMap = new HashMap<>();  //存放不同的角色登录成功后跳转到的页面，在此默认写死
		authDispatcherMap.put("ROLE_ADMIN", "/adminLoginSuccess");
		authDispatcherMap.put("ROLE_USER", "/loginSuccess");
		//根据用户的权限跳转到不同的页面
		if(url==null) {
			for(GrantedAuthority auth:authCollection) {
				url = authDispatcherMap.get(auth.getAuthority());
			}
			if (response.isCommitted()) {
				System.out.println("Can't redirect");
				return;
			}
			getRedirectStrategy().sendRedirect(request, response, url);
		}
		System.out.println("登录成功后的请求："+url);
		//super.onAuthenticationSuccess(request, response, authentication);
	}

}
